package com.liuya.safe.system.role.controller;

import com.liuya.common.StringUtil;
import com.liuya.common.Util;
import com.liuya.common.WebUtil;
import com.liuya.safe.model.SafeRole;
import com.liuya.safe.system.role.service.RoleManagerService;

import com.liuya.safe.util.Constants;
import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liuya.base.BaseController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Iterator;


/**
 * 角色管理
 * @author liuya
 * @date 20160826
 */
@Controller
@Api(value = "角色管理", description = "角色管理")
@RequestMapping(value = "roleMng")
public class RoleManagerContrller extends BaseController{

    @Autowired
    RoleManagerService roleManagerService;

    @ApiOperation(value = "角色列表页面")
//    @RequiresPermissions("sys.queryPolicy.rawSql")
    @RequestMapping(value = "/roleList")
    public Object roleList(HttpServletRequest req, HttpServletResponse rep, ModelMap map){
        // display from
        int first = WebUtil.getIntParameter(req, "first", 0);
        // display max size
        int size = WebUtil.getIntParameter(req, "size", Constants.DEFAULT_SHOW_ENTITY_SIZE);
        // search key
        String searchName = req.getParameter("name");
//        if (searchName != null) {
//            searchName = new String(searchName.getBytes("ISO-8859-1"), "UTF-8");
//        }

        Collection allRoles = null;
        int totalNumber = 0;
        if (StringUtil.isEmpty(searchName)) {
            allRoles = roleManagerService.getAllRoles();
        } else {
            allRoles = roleManagerService.getLikelyRoles(searchName);
        }

        totalNumber = allRoles.size();
        Collection roles = Util.sub(allRoles, first, size);

        map.addAttribute("totalNumber", totalNumber);
        map.addAttribute("roles", roles);
        map.addAttribute("first", first);
        map.addAttribute("size", size);
        map.addAttribute("name", searchName);

        return "system/roleList";
    }

    @ApiOperation(value = "跳转到角色添加页面")
//    @RequiresPermissions("sys.queryPolicy.rawSql")
    @RequestMapping(value = "/addRole")
    public Object addRole(HttpServletRequest req, HttpServletResponse rep, ModelMap map){
        return "system/editRole";
    }

    @ApiOperation(value = "验证名称是否有效")
//    @RequiresPermissions("sys.queryPolicy.rawSql")
    @RequestMapping(value = "/save")
    @ResponseBody
    public boolean save(HttpServletRequest req, HttpServletResponse rep, ModelMap map) {
        String name = req.getParameter("roleName");
        String description = req.getParameter("description");

        SafeRole role = new SafeRole();
        role.setDescription(description);
        role.setName(name);
        try{
            roleManagerService.addRole(role);
        } catch (Exception e){
            return false;
        }
        return true;
    }

    @ApiOperation(value = "验证名称是否有效")
//    @RequiresPermissions("sys.queryPolicy.rawSql")
    @RequestMapping(value = "/deleteRole")
    @ResponseBody
    public boolean deleteRole(HttpServletRequest req, HttpServletResponse rep, ModelMap map) {
        try{
            roleManagerService.deleteRole(WebUtil.getStringParameter(req, "id", "0"));
        } catch (Exception e){
            return false;
        }
        return true;
    }

    @ApiOperation(value = "验证名称是否有效")
//    @RequiresPermissions("sys.queryPolicy.rawSql")
    @RequestMapping(value = "/updateRole")
    @ResponseBody
    public boolean updateRole(HttpServletRequest req, HttpServletResponse rep, ModelMap map) {
        try{
            String name = req.getParameter("roleName");
            String description = req.getParameter("description");
            String id = WebUtil.getStringParameter(req, "id", "0");

            SafeRole role = new SafeRole();
            role.setDescription(description);
            role.setName(name);
            role.setId(id);
            roleManagerService.updateRole(role);
        } catch (Exception e){
            return false;
        }
        return true;
    }

    @ApiOperation(value = "获取角色")
//    @RequiresPermissions("sys.queryPolicy.rawSql")
    @RequestMapping(value = "/getRole")
    public Object getRole(HttpServletRequest req, HttpServletResponse rep, ModelMap map){
        String id = WebUtil.getStringParameter(req, "id", "0");
        SafeRole role = roleManagerService.getRole(id);
        map.addAttribute("role", role);
        return "system/editRole";
    }

    @ApiOperation(value = "验证名称是否有效")
//    @RequiresPermissions("sys.queryPolicy.rawSql")
    @RequestMapping(value = "/isNameValid")
    public void isNameValid(HttpServletRequest req, HttpServletResponse rep, ModelMap map) throws IOException {
        String name = req.getParameter("name");
        String strId = req.getParameter("id");

        SafeRole existRole = null;
        Collection roles = roleManagerService.getAllRoles();
        for (Iterator iter = roles.iterator(); iter.hasNext();) {
            SafeRole role = (SafeRole) iter.next();
            if (role.getName().equals(name)) {
                existRole = role;
                break;
            }
        }

        boolean valid = false;
        if (existRole == null || (existRole.getId() + "").equals(strId)) {
            valid = true;
        }

        rep.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = rep.getWriter();
        writer.write(valid + "");
        writer.flush();
        return;
    }

}
